package com.hntxk.cqzd.diagnosis.action;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hntxk.core.framework.model.OperModel;
import com.hntxk.core.framework.model.ResponseModel;
import com.hntxk.core.framework.model.ResultModel;
import com.hntxk.core.util.JsonUtil;
import com.hntxk.core.util.StringUtil;
import com.hntxk.cqzd.common.action.CqzdBaseController;
import com.hntxk.cqzd.diacrisis.entity.TblDiacrisisInfo;
import com.hntxk.cqzd.diagnosis.model.DiagnosisFruit;
import com.hntxk.cqzd.diagnosis.model.DiagnosisInfo;
import com.hntxk.cqzd.diagnosis.service.DiagnosisInfoService;
import com.hntxk.cqzd.lis.model.LisModel;
import com.hntxk.cqzd.lis.service.LisInterfaceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.swing.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 *  诊断结果controller类
 *  
 * @author Huang.Biquan
 * @date 2019年10月17日 10点09分
 */
@Api(value="诊断结果控制器", tags={"[CQZD]诊断结果接口"})
@Controller
@RequestMapping("cqzd/do/diagnosis")
public class DiagnosisInfoController extends CqzdBaseController {


	private final DiagnosisInfoService service;
    @Qualifier("LisInterfaceServiceImpl")
    @Autowired
    LisInterfaceService lisService;
	@Autowired
	public DiagnosisInfoController(@Qualifier("diagnosisInfoServiceImpl") DiagnosisInfoService service) {
		super(service, LogManager.getLogger(DiagnosisInfoController.class));
		this.service = service;
	}

	/**
	 * 获取诊断结果内容
	 *
	 * @return
	 */
    @ApiOperation(value="获取诊断结果内容",notes = "产前诊断系统")
	@ApiImplicitParam(name = "id", value = "诊断结果id",example = "1",required = true, dataTypeClass = Long.class)
	@GetMapping(value = "/get/{id}", produces= PRODUCE_UTF8_JSON)
	@ResponseBody
	public DiagnosisInfo get(@PathVariable("id") String id){
		return service.get(toLong(id));
	}

	/**
	 * 获取诊断记录的所有结果
	 *
	 * @return
	 */
	@ApiOperation(value="获取诊断记录的所有结果",notes = "产前诊断系统")
	@ApiImplicitParam(name = "id", value = "诊断记录id",example = "1",required = true, dataTypeClass = Long.class)
	@GetMapping(value = "/getByDiacrisis/{diacrisisId}", produces= PRODUCE_UTF8_JSON)
	@ResponseBody
	public ResponseModel getByDiacrisis(@PathVariable("diacrisisId") Long diacrisisId) {
		DiagnosisInfo model = new DiagnosisInfo();
		model.setDiacrisisId(diacrisisId);
		DiagnosisInfo bu = new DiagnosisInfo();
		//设置分页信息
		model.setPagination(request);
		List<DiagnosisInfo> diagnosisInfo = service.query(model);
		//获取诊断信息
		TblDiacrisisInfo diacrisisInfo = service.getDiacrisisService().get(diacrisisId);


		ResponseModel responseModel = ResponseModel.of(diagnosisInfo);
		responseModel.put("diacrisisInfo", diacrisisInfo);
		/*
		* 1.获取LIS系统中的该患者的报告信息
		* 2.将相同的报告做区分
		*
		*
		* */


        String[] array = {"羊水","绒毛","流产物","脐血"};

		List<LisModel> lis = lisService.getLis(diacrisisInfo.getPatientCardId(), null);
		Iterator ite = lis.iterator();
		while (ite.hasNext()){
            LisModel lisModel = (LisModel)ite.next();
            List<String> types = lisModel.getTypes();
            if (null!= types && types.size()>0){
                for (String typ:types) {
                    if (!Arrays.asList(array).contains(typ)){
                        ite.remove();
                    }
                }
            }
        }
		if (1==1){
			if (lis.size()>0){
				responseModel.put("lis",lis);
			}else {
				responseModel.put("lis",null);
			}
			return responseModel;
		}

		if (diagnosisInfo.isEmpty()) {

			/*根据OutPatientNo区分数据，如果后期通过f1f2区分可以直接该*/
			List<LisModel> ceshi = lis;
			List<List<LisModel>> lilist = new ArrayList<>();
			while (ceshi.size() > 0) {
				List<LisModel> zc = new ArrayList<>();
				String outPatientNo = ceshi.get(0).getOutPatientNo();
				Iterator it = ceshi.iterator();
				while (it.hasNext()) {
					LisModel md = (LisModel) it.next();
					if (outPatientNo.equals(md.getOutPatientNo())) {
						zc.add(md);
						it.remove();
					}
				}
				for (int i = 0; i < ceshi.size(); i++) {

					if (outPatientNo.equals(ceshi.get(i).getOutPatientNo())) {
						zc.add(ceshi.get(i));
					}

				}
				lilist.add(zc);
			}

			int j = 1;
			for (List<LisModel> listMd : lilist) {
				/*如果查询实验室结果没数据lis系统有数据new实验室结果对象显示到页面保存
        		                    没有数据不执行操作
        * 如果查询实验室结果有数据则不执行操作*/

				if (listMd.size() > 0) {
					DiagnosisInfo dInfo = new DiagnosisInfo();
					List<DiagnosisFruit> diagnosisFruit = new ArrayList<>();
					DiagnosisFruit fishFruit = new DiagnosisFruit();
					fishFruit.setFruitTypeName("FISH");
					DiagnosisFruit cnvFruit = new DiagnosisFruit();
					cnvFruit.setFruitTypeName("CNV");
					DiagnosisFruit otherFruit = new DiagnosisFruit();
					otherFruit.setFruitTypeName("其他");
					DiagnosisFruit heFruit = new DiagnosisFruit();
					heFruit.setFruitTypeName("核型分析");
					for (int i = 0; i < listMd.size(); i++) {
						LisModel lismd = listMd.get(i);
//							if (diacrisisInfo.getOutpatientNo().equals(lismd.getOutPatientNo())){
						if (lismd.getCategoryCode().contains("染色体分析")) {
							heFruit.setFruitExplain(lismd.getResult());
						}
						if (lismd.getCategoryCode().contains("细胞荧光原位杂交检测")) {
							fishFruit.setFruitExplain(lismd.getResult());
						}
//					筛选OutPatientNo
                        if (!lismd.getTypes().isEmpty()&&lismd.getTypes().size()>0){
                            switch (lismd.getTypes().get(0)) {
                                case "羊水":
                                    dInfo.setDiacrisisId(diacrisisInfo.getDiacrisisId());
                                    dInfo.setInspectionTime(lismd.getEffectiveDateTime());
                                    dInfo.setInspectionItem("羊穿");
                                    dInfo.setInspectionItemId((long) 1);
                                    break;
                                case "绒毛":
                                    dInfo.setDiacrisisId(diacrisisInfo.getDiacrisisId());
                                    dInfo.setInspectionTime(lismd.getEffectiveDateTime());
                                    dInfo.setInspectionItem("绒穿");
                                    dInfo.setInspectionItemId((long) 3);
                                    break;
                                case "流产物":
                                    dInfo.setDiacrisisId(diacrisisInfo.getDiacrisisId());
                                    dInfo.setInspectionTime(lismd.getEffectiveDateTime());
                                    dInfo.setInspectionItem("样本留存");
                                    dInfo.setInspectionItemId((long) 4);
                                    break;
                                case "脐血":
                                    dInfo.setDiacrisisId(diacrisisInfo.getDiacrisisId());
                                    dInfo.setInspectionTime(lismd.getEffectiveDateTime());
                                    dInfo.setInspectionItem("脐穿");
                                    dInfo.setInspectionItemId((long) 2);
                                    break;
                                default:
                            }
                        }
						dInfo.setDiagnosisFruit(diagnosisFruit);
						dInfo.setFetusSign("F" + j);

					}

//						}
					diagnosisFruit.add(fishFruit);
					diagnosisFruit.add(cnvFruit);
					diagnosisFruit.add(otherFruit);
					diagnosisFruit.add(heFruit);
					if (ObjectUtils.isNotEmpty(dInfo))
						diagnosisInfo.add(dInfo);
					bu = dInfo;
				}
				j++;
			}
		}
		if (diagnosisInfo.size()>0){
			while (diacrisisInfo.getFetusesNo() > (diagnosisInfo.size())) {
				diagnosisInfo.add(diagnosisInfo.get(0));
			}
		}
		responseModel.put("diacrisisInfo", diacrisisInfo);
		return responseModel;
	}
	

	/**
	 *  保存诊断结果
	 * @param infoList List<DiagnosisInfo>
	 * @return 保存失败提示
	 */
	@ApiOperation(value="保存诊断结果",notes = "产前诊断系统")
	@ApiImplicitParam(name = "json", value = "JSON字符串参数",required = true,example = "[{\n" +
			"    \"diacrisisId\":1,\n" +
			"    \"inspectionItemId\":1,\n" +
			"    \"inspectionItem\":\"羊水穿刺\",\n" +
			"    \"inspectionTime\":\"2019-10-23 09:59:03\",\n" +
			"    \"afTypeId\":1,\n" +
			"    \"afTypeName\":\"清亮\",\n" +
			"    \"inspectionProcess\":\"datagrip自定义新增驱动可以\",\n" +
			"    \"inspectionRemark\":\"1折起1折起1折起，重要的事情说三遍！\",\n" +
			"    \"fetusSign\":\"F1\",\n" +
			"    \"bSign\":\"FB1\",\n" +
			"    \"puncturePosition\":\"SJDFLSKF\",\n" +
			"    \"mazaPosition\":\"LEFT\",\n" +
			"    \"sampleQuantity\":2.45,\n" +
			"    \"diagnosisFruit\":[\n" +
			"        {\n" +
			"            \"fruitTypeId\":1,\n" +
			"            \"fruitTypeName\":\"FISH\",\n" +
			"            \"fruitExplain\":\"AAIDD\"\n" +
			"        }\n" +
			"    ]\n" +
			"}]",dataTypeClass = String.class)
	@PostMapping(value = "/save", produces= PRODUCE_UTF8_JSON)
	@ResponseBody
	public String save(@RequestBody ArrayList<DiagnosisInfo> infoList){

		ResultModel resultModel = service.save(infoList);
		return resultModel.hasError()?responseSorry(resultModel.getErrMsg()):responseOk();
	}


	/**
	 * 删除诊断记录的诊断结果
	 * @return 删除失败提示
	 */
    @Override
	@ApiOperation(value="删除诊断记录的诊断结果",notes = "产前诊断系统")
	@ApiImplicitParam(name = "diacrisisId", value = "诊断记录ID",required = true,example = "1",dataTypeClass = String.class)
	@DeleteMapping(value = "/delete/{diacrisisId}", produces= PRODUCE_UTF8_JSON)
	@ResponseBody
	public String delete(@PathVariable String diacrisisId){

		String msg = service.delete(diacrisisId, new OperModel());
		if (null == msg){
			return responseOk();
		}
		return responseSorry(msg);
	}


	/**
	 *  查询诊断记录
	 *
	 * 用于诊断结果登记页面的右侧菜单列表【诊断记录列表】
	 * @param key 部分消息内容【模糊查找】
	 * @return {histories:[已经登记过诊断结果的诊断记录],todoList:[未登记过诊断结果的诊断记录]}
	 */
	@ApiOperation(value="查询诊断记录",notes = "产前诊断系统")
	@ApiImplicitParam(name = "key", value = "部分消息内容【模糊查找】",example = "你好",required = false, dataTypeClass = String.class)
	@RequestMapping(value = "/listDiacrisis", method = {RequestMethod.GET,RequestMethod.POST}, produces= PRODUCE_UTF8_JSON)
	@ResponseBody
	public ResponseModel listDiacrisis(@RequestParam(required = false) String key) {
		TblDiacrisisInfo diacrisisInfo = new TblDiacrisisInfo();
		if (StringUtil.isNotNull(key)){
			if (key.length()<4){
				diacrisisInfo.setPatientName(key);
			}else{
				diacrisisInfo.getProp().put("key",key);
			}
		}
		return service.listDiacrisis(diacrisisInfo);
	}
}
